<?php


namespace App\Http\Controllers\Admin\RedPacket;


use App\Response\Response;
use Illuminate\Http\Request;
use App\Services\Tools\Export;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
//私聊红包
class PrivateRedPacketController extends BaseController
{
    /**
     * @api {post} /private-red-packet/user 增加白名单用户
     * @apiVersion 3.6.3
     * @apiGroup 私聊红包
     * @apiParam {int} user_code 用户ID，必须
     * @apiSuccessExample 成功响应
     * {"code":200,"data":[],"message":""}
     */
    public function addUser(Request $request)
    {
        $params = $request->only('user_code');
        $v = app('validator')->make($params, [
            'user_code' => 'required|integer|min:1|max:2100000000'
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $userCode = $params['user_code'];
        //查询用户信息
        $userData = app('model_user_data')->getInfoByUserCode($userCode, ['ud.user_id']);
        if (empty($userData)) throw new BasicException(0, '用户ID不存在');

        $privateChatRpUser = app('model_private_chat_rp_user')
            ->select('is_remove')
            ->where('user_id', $userData->user_id)
            ->first();
        if ($privateChatRpUser) {
            if ($privateChatRpUser->is_remove == 1) {
                app('model_private_chat_rp_user')->where('user_id', $userData->user_id)->update(['is_remove' => 0]);
            } else {
                throw new BasicException(0, '该用户已在白名单中');
            }
        } else {
            app('model_private_chat_rp_user')->insert([
                'user_id' => $userData->user_id,
                'admin_id' => app('request')->admin_id,
            ]);
        }
        return Response::sendData([]);
    }

    /**
     * @api {put} /private-red-packet/remove-user 移除白名单用户
     * @apiVersion 3.6.3
     * @apiGroup 私聊红包
     * @apiParam {int} user_id 用户索引id，非user_code，必须
     * @apiSuccessExample 成功响应
     * {"code":200,"data":[],"message":""}
     */
    public function removeUser(Request $request)
    {
        $params = $request->only('user_id');
        $v = app('validator')->make($params, [
            'user_id' => 'required|integer|min:1|max:2100000000'
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $userId = $params['user_id'];

        $redPacketUser = app('model_private_chat_rp_user')->select('is_remove')->where('user_id', $userId)->first();
        if ($redPacketUser) {
            if ($redPacketUser->is_remove == 0) {
                app('model_private_chat_rp_user')->where('user_id', $userId)->update(['is_remove' => 1]);
            } else {
                throw new BasicException(0, '用户已不在白名单');
            }
        } else {
            throw new BasicException(0, '不存在的用户id');
        }
        return Response::sendData([]);
    }

    /**
     * @api {get} /private-red-packet/user 私聊红包用户列表
     * @apiVersion 3.6.3
     * @apiGroup 私聊红包
     * @apiParam {string} create_time_start 添加时间开始，yyyy-mm-dd
     * @apiParam {string} create_time_end 添加时间结束，yyyy-mm-dd
     * @apiParam {string} update_time_start 更新时间开始，yyyy-mm-dd
     * @apiParam {string} update_time_end 更新时间结束，yyyy-mm-dd
     * @apiParam {int} user_code 用户ID
     * @apiParam {string} nickname 用户昵称
     * @apiParam {int} page 第几页，默认1
     * @apiParam {int} page_size 每页显示条数，1~100，默认10
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "user_id": 547176, 编号（用户索引id）
    "money_total": "0.00", 累计发红包金额（气泡币）
    "admin_id": 1,
    "created_at": "2021-11-24 15:28:48", 添加时间
    "updated_at": "2021-11-24 15:28:48", 更新时间
    "user_code": 999981, 用户ID
    "nickname": "111CK有", 用户昵称
    "operator": "李明兴" 操作人
    }
    ],
    "first_page_url": "http://qipaoadmin/private-red-packet/user?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://qipaoadmin/private-red-packet/user?page=1",
    "next_page_url": null,
    "path": "http://qipaoadmin/private-red-packet/user",
    "per_page": 10,
    "prev_page_url": null,
    "to": 1,
    "total": 1
    },
    "message": ""
    }
     */
    public function userList(Request $request)
    {
        $params = $request->only('create_time_start', 'create_time_end', 'update_time_start', 'update_time_end', 'user_code', 'nickname', 'page_size');
        $v = app('validator')->make($params, [
            'create_time_start' => 'date_format:Y-m-d',
            'create_time_end' => 'date_format:Y-m-d',
            'update_time_start' => 'date_format:Y-m-d',
            'update_time_end' => 'date_format:Y-m-d',
            'user_code' => 'integer|min:1|max:2100000000',
            'nickname' => 'string|min:1|max:20',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $createTimeStart = $params['create_time_start'] ?? '';
        $createTimeEnd = $params['create_time_end'] ?? '';
        $updateTimeStart = $params['update_time_start'] ?? '';
        $updateTimeEnd = $params['update_time_end'] ?? '';
        $userCode = $params['user_code'] ?? 0;
        $nickname = $params['nickname'] ?? '';
        $pageSize = $params['page_size'] ?? 10;

        $where = [];
        $whereFunc = [];
        if ($createTimeStart) {
            $where[] = ['created_at', '>=', $createTimeStart . ' 00:00:00'];
        }
        if ($createTimeEnd) {
            $where[] = ['created_at', '<=', $createTimeEnd . ' 23:59:59'];
        }
        if ($updateTimeStart) {
            $where[] = ['updated_at', '>=', $updateTimeStart . ' 00:00:00'];
        }
        if ($updateTimeEnd) {
            $where[] = ['updated_at', '<=', $updateTimeEnd . ' 23:59:59'];
        }
        if ($userCode) {
            $userId = app('model_user_data')->where('user_code', $userCode)->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        if ($nickname) {
            $userIds = app('model_user_data')->where('nickname', 'like', "%$nickname%")->pluck('user_id')->toArray();
            $whereFunc = function ($query) use ($userIds) {
                $query->whereIn('user_id', $userIds);
            };
        }

        $list = app('model_private_chat_rp_user')
            ->select('user_id', 'money_total', 'admin_id', 'created_at', 'updated_at')
            ->where($where)
            ->where($whereFunc)
            ->where('is_remove', 0)
            ->orderByDesc('created_at')
            ->paginate($pageSize)->toArray();

        //批量查询用户ID和昵称
        $userIds = array_column($list['data'], 'user_id');
        $userDatas = app('model_user_data')->batchQueryByUserIdMap($userIds);
        //批量查询管理员
        $adminIds = array_column($list['data'], 'admin_id');
        $admins = app('model_admin')->select('realname', 'admin_id')
            ->whereIn('admin_id', $adminIds)
            ->pluck('realname', 'admin_id')->toArray();

        foreach ($list['data'] as &$v) {
            $v['user_code'] = $userDatas[$v['user_id']]['user_code'] ?? '';
            $v['nickname'] = $userDatas[$v['user_id']]['nickname'] ?? '';
            $v['operator'] = $admins[$v['admin_id']] ?? '';
        }
        return Response::sendData($list);
    }

    /**
     * @api {get} /private-red-packet/records 发红包记录
     * @apiVersion 3.6.3
     * @apiGroup 私聊红包
     * @apiParam {string} create_time_start 创建时间开始，yyyy-mm-dd
     * @apiParam {string} create_time_end 创建时间结束，yyyy-mm-dd
     * @apiParam {int} user_code 发红包用户ID
     * @apiParam {string} nickname 发红包用户昵称
     * @apiParam {int} status 状态：-1（默认）：不限制；0：未领取；1：已领取；2：已失效
     * @apiParam {int} page 第几页，默认1
     * @apiParam {int} page_size 每页显示条数，1~100，默认10
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 1, 编号
    "send_user_id": 547181,
    "receive_user_id": 547182,
    "money": "888.00", 红包金额（气泡币）
    "status": 0, 状态
    "created_at": "2021-11-24 21:00:04", 创建时间
    "send_user_code": 856433, 发红包用户ID
    "send_nickname": "54646", 发红包用户昵称
    "receive_user_code": 187698, 领红包用户ID
    "receive_nickname": "✧≖◡✿殇", 领红包用户昵称
    "status_desc": "未领取" 状态描述
    }
    ],
    "first_page_url": "http://qipaoadmin/private-red-packet/records?page=1",
    "from": 1,
    "last_page": 3,
    "last_page_url": "http://qipaoadmin/private-red-packet/records?page=3",
    "next_page_url": "http://qipaoadmin/private-red-packet/records?page=2",
    "path": "http://qipaoadmin/private-red-packet/records",
    "per_page": "1",
    "prev_page_url": null,
    "to": 1,
    "total": 3
    },
    "message": ""
    }
     */
    public function records(Request $request)
    {
        $params = $request->only('create_time_start', 'create_time_end', 'user_code', 'nickname', 'status', 'page_size');
        $v = app('validator')->make($params, [
            'create_time_start' => 'date_format:Y-m-d',
            'create_time_end' => 'date_format:Y-m-d',
            'user_code' => 'integer|min:1|max:2100000000',
            'nickname' => 'string|min:1|max:20',
            'status' => 'integer|in:-1,0,1,2',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $list = app('repo_red_packet')->getPrivateRedPacketRecords($params);
        return Response::sendData($list);
    }

    /**
     * @api {get} /private-red-packet/records/export 发红包记录导出
     * @apiVersion 3.6.3
     * @apiGroup 私聊红包
     * @apiParam {string} create_time_start 创建时间开始，yyyy-mm-dd
     * @apiParam {string} create_time_end 创建时间结束，yyyy-mm-dd
     * @apiParam {int} user_code 发红包用户ID
     * @apiParam {string} nickname 发红包用户昵称
     * @apiParam {int} status 状态：-1（默认）：不限制；0：未领取；1：已领取；2：已失效
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": "https://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/export_data/private_red_packet-20211130-155102-921.xls",
    "message": ""
    }
     */
    public function recordsExport(Request $request)
    {
        $params = $request->only('create_time_start', 'create_time_end', 'user_code', 'nickname', 'status', 'page_size');
        $v = app('validator')->make($params, [
            'create_time_start' => 'date_format:Y-m-d',
            'create_time_end' => 'date_format:Y-m-d',
            'user_code' => 'integer|min:1|max:2100000000',
            'nickname' => 'string|min:1|max:20',
            'status' => 'integer|in:-1,0,1,2',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $list = app('repo_red_packet')->getPrivateRedPacketRecords($params, 0);
        $fields = [
            ['field' => 'id', 'header' => '编号', 'width' => 14],
            ['field' => 'send_user_code', 'header' => '用户ID', 'width' => 16],
            ['field' => 'send_nickname', 'header' => '用户昵称', 'width' => 20],
            ['field' => 'money', 'header' => '红包冰语币', 'width' => 16],
            ['field' => 'receive_user_code', 'header' => '接收者用户ID', 'width' => 16],
            ['field' => 'receive_nickname', 'header' => '接收者用户昵称', 'width' => 20],
            ['field' => 'status_desc', 'header' => '红包状态', 'width' => 16],
            ['field' => 'created_at', 'header' => '创建时间', 'width' => 20],
        ];
        $res = Export::exportUsePhpOffice('private_red_packet', $fields, $list);
        return Response::sendData($res);
    }
}
